package com.yiren.dbaa.net.oss.impl;

import android.content.Context;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.GetObjectRequest;
import com.alibaba.sdk.android.oss.model.GetObjectResult;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.net.interf.OssFileCallback;
import com.yiren.dbaa.net.oss.IOssFileOperationApi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.net.ssl.SSLHandshakeException;

/**
 * Time:2022/5/24 11:29
 * Author:xiaozan
 * Description:oss 文件操作业务实现
 */
public class OssFileOperationApiImpl implements IOssFileOperationApi {

    private Context context;
    private OSS oss;
    private OSSCredentialProvider credentialProvider;

    /**
     * 不需要文件授权凭证
     */
    public OssFileOperationApiImpl(Context context) {
        this.context = context;
        credentialProvider = new OSSCredentialProvider() {
        };
        oss = new OSSClient(context, AddressConstant.ALIYUN_OSS_MAIN_URL, credentialProvider);
    }

    /**
     * 需要文件授权凭证
     *
     * @param accessKeyId
     * @param accessKeySecret
     * @param securityToken
     */
    public OssFileOperationApiImpl(Context context, String accessKeyId, String accessKeySecret, String securityToken) {
        this.context = context;
        credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        oss = new OSSClient(context, AddressConstant.ALIYUN_OSS_MAIN_URL, credentialProvider);
    }

    @Override
    public void downLoadFile(String bucketName, String objectKey, String sdkDownUrl, String fileName, OssFileCallback iOssFileCallback) {
        GetObjectRequest get = new GetObjectRequest(bucketName, objectKey);
        oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @SuppressWarnings("resource")
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                InputStream inputStream = null;
                OutputStream os = null;
                iOssFileCallback.contentLength(result.getContentLength());
                try {
                    File file = new File(sdkDownUrl, fileName);
                    if (!file.exists()) {
                        file.getParentFile().mkdirs();
                        file.createNewFile();
                    }
                    // 请求成功
                    inputStream = result.getObjectContent();
                    byte[] buffer = new byte[2048];
                    os = new FileOutputStream(file);
                    int len;
                    while ((len = inputStream.read(buffer)) != -1) {
                        os.write(buffer, 0, len);
                        //更新长度
                        iOssFileCallback.progress(len);
                    }
                    //下载弯沉
//                    ((Activity) context).runOnUiThread(() -> {
                    iOssFileCallback.success("");
//                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    AddressConstant.ALY_SERVER_IP = "http://api.dj23.cn/";
                    AddressConstant.APK_UPDATE_URL = "http://oss-cn-shenzhen.aliyuncs.com";
                    AddressConstant.ALIYUN_OSS_MAIN_URL = "http://oss-cn-shenzhen.aliyuncs.com";
                } finally {
                    try {
                        if (null != os) os.close();
                        if (null != inputStream) inputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                String excepionStr = "";
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    excepionStr += clientExcepion.getMessage();
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    excepionStr += serviceException.getMessage();
                }
                iOssFileCallback.fail(excepionStr);
            }
        });
    }

    @Override
    public void downLoadTxtFile(String bucketName, String objectKey, OssFileCallback iOssFileCallback) {
        GetObjectRequest get = new GetObjectRequest(bucketName, objectKey);
        oss.asyncGetObject(get, new OSSCompletedCallback<GetObjectRequest, GetObjectResult>() {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                InputStream inputStream = result.getObjectContent();
                StringBuffer out = new StringBuffer();
                byte[] b = new byte[1024];
                int n;
                try {
                    while ((n = inputStream.read(b)) != -1) {
                        out.append(new String(b, 0, n));
                    }
                    iOssFileCallback.success(out.toString());
                    inputStream.close();
                } catch (SSLHandshakeException e) {
                    AddressConstant.ALY_SERVER_IP = "http://api.dj23.cn/";
                    AddressConstant.APK_UPDATE_URL = "http://oss-cn-shenzhen.aliyuncs.com";
                    AddressConstant.ALIYUN_OSS_MAIN_URL = "http://oss-cn-shenzhen.aliyuncs.com";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(GetObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                String excepionStr = "";
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    excepionStr += clientExcepion;
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    excepionStr += serviceException;
                }
                iOssFileCallback.fail(excepionStr);
            }
        });
    }

    @Override
    public void uploadFile(String bucketName, String objectKey, String uploadFilePath, OssFileCallback iOssFileCallback) {
        // 构造上传请求5
        //dj-create-data
        PutObjectRequest put = new PutObjectRequest(bucketName, objectKey, uploadFilePath);
        oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                iOssFileCallback.success("");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                String excepionStr = "";
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    excepionStr += clientExcepion;
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                    excepionStr += serviceException;
                }
                iOssFileCallback.fail(excepionStr);
            }
        });
    }
}
